<!--
 * @Author: 曹捷
 * @Date: 2020-12-03 09:34:33
 * @LastEditors: 曹捷
 * @LastEditTime: 2021-02-02 20:36:23
 * @Description: 加入购物车效果
 初始化目标选择器
 调用起始位置选择器
-->
<template>
  <view class="relative">
    <view class="ball" v-for="(d,i) in balls" :key="i"
      :style=" d.inited ? 'transition: transform .4s cubic-bezier(.6,-0.63,.94,.71); transform: translate3d(0, ' + offsetY + 'px,0); top: ' + ballY + 'px;' : '' ">
      <view class="inner arbg"
        :style="d.inited ? 'transition: transform .4s linear; transform: translate3d( ' + offsetX + 'px,0,0); left: ' + ballX + 'px; opacity: 1;' : '' ">
      </view>
    </view>
  </view>
</template>
 
<script>
export default {
  props: {
    // 选择器  #id  .class
    select: {
      type: String
    }
  },
  data () {
    return {
      offsetX: 0,
      offsetY: 0,
      ballX: 0,
      ballY: 0,
      balls: {},
      //避免抖动
      lastEvent: '',
      lastId: '',
      cartBasketRect: {}
    }
  },
  created () {
    let balls = [];
    for (let i = 0; i < 5; i++) {
      balls.push({ inited: false });
    }
    this.balls = balls
  },
  methods: {
    getBalls () {
      return balls;
    },
    toCarById (id) {
      let q = uni.createSelectorQuery()
      q.select(id).boundingClientRect(res => {
        this.addToCart(res);
      }).exec();
    },
    addToCart (e, id) {
      // console.log('e: ', e);
      const self = this
      let ballX = e.left
      let ballY = e.top
      this.offsetX = this.cartBasketRect.left - ballX + this.cartBasketRect.width / 2
      this.offsetY = this.cartBasketRect.top - ballY + (this.cartBasketRect.height / 1.5)
      this.ballX = ballX
      this.ballY = ballY
      for (let i = 0; i < 5; i++) {
        if (!this.balls[i].inited) {
          this.balls[i].inited = true
          setTimeout(() => {
            self.balls[i].inited = false
          }, 500);
          break;
        }
      }
    },
    initEndPostion () {
      let q = uni.createSelectorQuery()
      let that = this
      q.select(that.select).boundingClientRect(data => {
        // console.log('🚀 ~ file: flyInCar.vue ~ line 82 ~ q.select ~ data', data)
        that.cartBasketRect = data
      }).exec();
    }
  },
  mounted () {
    setTimeout(() => {
      this.initEndPostion()
    }, 200)
  }


}
</script>

 
<style scoped>
.ball {
  position: fixed;
  z-index: 99999;
}
.ball .inner {
  background: #ff5722;
  width: 15px;
  height: 15px;
  position: fixed;
  border-radius: 50%;
  opacity: 0;
}
</style> 